package com.zhonghui.wms.controller;

import com.zhonghui.common.annotation.Log;
import com.zhonghui.common.core.controller.BaseController;
import com.zhonghui.common.core.page.TableDataInfo;
import com.zhonghui.common.enums.BusinessType;
import com.zhonghui.common.utils.DateUtils;
import com.zhonghui.common.utils.SecurityUtils;
import com.zhonghui.common.utils.StringUtils;
import com.zhonghui.common.utils.poi.ExcelUtil;
import com.zhonghui.response.BaseResult;
import com.zhonghui.wms.domain.WmsRelocationInformation;
import com.zhonghui.wms.domain.vo.WmsInventoryDetailsVo;
import com.zhonghui.wms.domain.vo.WmsRelocationInformationVo;
import com.zhonghui.wms.service.IWmsInventoryDetailsService;
import com.zhonghui.wms.service.IWmsRelocationInformationService;
import com.zhonghui.wms.service.IWmsWarehouseAreaService;
import com.zhonghui.wms.service.IWmsWarehouseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 智能仓储WMS-移库信息Controller
 *
 * @author zhonghui
 * @date 2023-08-02
 */
@Api(tags="智能仓储WMS-移库信息")
@RestController
@RequestMapping("/wms/relocation")
public class WmsRelocationInformationController extends BaseController
{
    @Autowired
    private IWmsRelocationInformationService wmsRelocationInformationService;

    @Autowired
    private IWmsWarehouseService wmsWarehouseService;

    @Autowired
    private IWmsWarehouseAreaService wmsWarehouseAreaService;

    @Autowired
    private IWmsInventoryDetailsService wmsInventoryDetailsService;

    /**
     * 查询智能仓储WMS-移库信息列表
     */
    @ApiOperation("查询智能仓储WMS-移库信息列表")
    @GetMapping("/list")
    public TableDataInfo<List<WmsRelocationInformationVo>> list(WmsRelocationInformation wmsRelocationInformation)
    {
        startPage();
        List<WmsRelocationInformationVo> list = wmsRelocationInformationService.selectWmsRelocationInformationList(wmsRelocationInformation);
        return getDataTable(list);
    }

    /**
     * 导出智能仓储WMS-移库信息列表
     */
    @ApiOperation("导出智能仓储WMS-移库信息列表")
    @Log(title = "智能仓储WMS-移库信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WmsRelocationInformation wmsRelocationInformation)
    {
        List<WmsRelocationInformationVo> list = wmsRelocationInformationService.selectWmsRelocationInformationList(wmsRelocationInformation);
        ExcelUtil<WmsRelocationInformationVo> util = new ExcelUtil<WmsRelocationInformationVo>(WmsRelocationInformationVo.class);
        util.exportExcel(response, list, "智能仓储WMS-移库信息数据");
    }

    /**
     * 获取智能仓储WMS-移库信息详细信息
     */
    @ApiOperation("获取智能仓储WMS-移库信息详细信息")
    @GetMapping(value = "/{id}")
    public BaseResult<WmsRelocationInformation> getInfo(@PathVariable("id") Long id)
    {
        return BaseResult.success(wmsRelocationInformationService.selectWmsRelocationInformationById(id));
    }

    /**
     * 新增智能仓储WMS-移库信息
     */
    @ApiOperation("新增智能仓储WMS-移库信息")
    @Log(title = "智能仓储WMS-移库信息", businessType = BusinessType.INSERT)
    @PostMapping
    public BaseResult<Integer> add(@RequestBody WmsRelocationInformation wmsRelocationInformation)
    {
        return BaseResult.success(wmsRelocationInformationService.insertWmsRelocationInformation(wmsRelocationInformation));
    }

    /**
     * 修改智能仓储WMS-移库信息
     */
    @ApiOperation("修改智能仓储WMS-移库信息")
    @Log(title = "智能仓储WMS-移库信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public BaseResult<Integer> edit(@RequestBody WmsRelocationInformation wmsRelocationInformation)
    {
        return BaseResult.success(wmsRelocationInformationService.updateWmsRelocationInformation(wmsRelocationInformation));
    }

    /**
     * 删除智能仓储WMS-移库信息
     */
    @ApiOperation("删除智能仓储WMS-移库信息")
    @Log(title = "智能仓储WMS-移库信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public BaseResult<Integer> remove(@PathVariable Long[] ids)
    {
        return BaseResult.success(wmsRelocationInformationService.deleteWmsRelocationInformationByIds(ids));
    }

    /**
     * 批量新增智能仓储WMS-移库信息
     */
    @ApiOperation("批量新增智能仓储WMS-移库信息")
    @Log(title = "智能仓储WMS-移库信息", businessType = BusinessType.INSERT)
    @PostMapping("/relocation")
    public BaseResult<Integer> relocation(@RequestBody List<WmsRelocationInformation> wmsRelocationInformationList)
    {
        List<WmsRelocationInformation> resultList = new ArrayList<WmsRelocationInformation>();
        final StringBuilder msg = new StringBuilder();
        wmsRelocationInformationList.stream().filter(item -> {
            // 过滤前端传空字符串的情况
            if(item.getTargetWarehouse() != null && item.getTargetArea() != null && item.getTargetSeat() != null && item.getRelocationQuantity() != null){
                // 判断仓库中是否包含目标仓库
                if (item.getTargetWarehouse() != wmsWarehouseService.selectWmsWarehouseById(item.getTargetWarehouse()).getId()){
                    return false;
                }
                // 判断库区中是否包含目标库区
                if (item.getTargetArea() != wmsWarehouseAreaService.selectWmsWarehouseAreaById(item.getTargetArea()).getId()){
                    return false;
                }
                // 判断目标库位是否和源库位相同
                if (item.getTargetSeat() == item.getSourceSeat()){
                    return false;
                }
                // 如果为true，stream流的filter方法将会留用元素，如果结果为false，那么filter方法将会舍弃元素
                return true;
            }
            return false;
        }).forEach(item ->{
            WmsInventoryDetailsVo detailVos = new WmsInventoryDetailsVo();
            detailVos.setBatchNumber(item.getBatchNumber());
            detailVos.setWarehouseId(item.getSourceWarehouse());
            detailVos.setWarehouseAreaId(item.getSourceArea());
            detailVos.setWarehouseSeatId(item.getSourceSeat());
            detailVos.setMaterialId(item.getMaterialId());
            // 判断源仓库里的物料库存明细中是否包含该物料
            List<WmsInventoryDetailsVo> inventoryDetailsVoList = wmsInventoryDetailsService.selectWmsInventoryDetailsList(detailVos);
            if (inventoryDetailsVoList != null && !inventoryDetailsVoList.isEmpty()){
                WmsInventoryDetailsVo source = inventoryDetailsVoList.get(0);
                double total = source.getExistingInventory() == null ? 0 : source.getExistingInventory();
                double lock = source.getLockInventory() == null ? 0 : source.getLockInventory();
                if ( item.getRelocationQuantity() > total - lock) {
                    msg.append("移库数量大于物料库存数量,移库失败！");
                } else {
                    item.setTransferTime(DateUtils.getNowDate());
                    item.setExecutor(SecurityUtils.getLoginUser().getUserId());
                    resultList.add(item);
                }
            }else {
                msg.append("物料在源仓库中库存不足,移库失败！");
            }
        });
        if (StringUtils.isNotBlank(msg.toString())){
            return BaseResult.error(msg.toString());
        }
        wmsRelocationInformationService.batchWmsRelocationInformation(resultList);
        return BaseResult.success();
    }
}
